package cn._51doit.flink.day11;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * 使用Flink SQL实现实时的WordCount
 */
public class SqlWordCount2 {

    public static void main(String[] args) throws Exception {

        //创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //StreamTableEnvironment将原来的StreamExecutionEnvironment包装起来（增强）
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);

        //先创建普通的数据流
        //spark,1
        //spark,5
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String line) throws Exception {
                String[] fields = line.split(",");
                return Tuple2.of(fields[0], Integer.parseInt(fields[1]));
            }
        });

        //将DataStream转成Table或注册成视图
        tableEnvironment.createTemporaryView("tb_wc", wordAndOne, $("word"), $("counts"));
        Table table = tableEnvironment.sqlQuery("select word, sum(counts) counts from tb_wc group by word");

        DataStream<Tuple2<Boolean, Tuple2<String, Integer>>> res = tableEnvironment.toRetractStream(table, TypeInformation.of(new TypeHint<Tuple2<String, Integer>>() {}));

        res.print();

        env.execute();

    }
}
